<link rel="stylesheet" type="text/css" href="<?php echo css_url() . 'general_form.css' ?>">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="<?php echo css_url().'table/list_show.css'?>">
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<form id="edit-user-contact-form" action="<?php echo site_url() . '/user_group2/account/edit_user_contact' ?>" method="post">

    <input id="currentid" name="currentid" value="-2" type="hidden">
    <ol>
        <!----Website Link--!-->
        <div class="head">Websites:
            <div id="add-website" class="margin-left add-btn" style='position:relative; left:7%'>Add New</div>
            <div id="delete-website" class="margin-left add-btn" style='position:relative; left:13%'>-</div>
            <span class="error" id="website-error" style="position:relative; left:20%"></span>
        </div>
        <li>
            <div class="tab" id="websites-section">
                <?php
                $CI = & get_instance();
                $UserInfoTemp = $CI->db->get_where(MYSQL_TABLE_PREFLIX . TABLE_USER2_ACCOUNTS_INFORMATION, array('RelUserEmail' => $UserInfo['UserEmail']));
                $UserInfoTemp = $UserInfoTemp->result_array();
                $Websites = $UserInfoTemp[0]['Websites'];
                $Websites = explode("#", $Websites);
                foreach ($Websites as $Website):
                    ?>
                    <input value="<?php echo $Website ?>" class="text margin-bottom" name="Websites[]">
                <?php endforeach;
                ?>
            </div>
        </li>

        <!--Address Field-->
        <div class="head">Address: 
            <div id="add-address" class="margin-left add-btn" style='position:relative; left:8%'>Add New</div>
        </div>

        <li>
            <div>
                <?php
                $CI = & get_instance();
                $Locations = $CI->db->get_where(MYSQL_TABLE_PREFLIX . TABLE_USER2_CONTACT_INFORMATION, array('RelUserEmail' => $UserInfo['UserEmail']));
                $Locations = $Locations->result_array();
                $CI->load->library('table');
                $data = array(
                    array('Name', 'Province', 'City', 'District', 'Street', 'Phones'),
                );
                $i = 0;
                foreach ($Locations as $Location) {
                    //Strip Qualification Name
                    $Address = explode('#', $Location['Address']);
                    $PhoneString = "";
                    $Phones = explode('#', $Location['Phones']);
                    foreach ($Phones as $Phone) {
                        $PhoneString .= $Phone . " - ";
                    }
                    $PhoneString = substr($PhoneString, 0, -3);
                    $Describtion = $Location['Describtion'];
                    $data[] = array(
                        $Location['Name']
                        , $Address[0]
                        , $Address[1]
                        , $Address[2]
                        , $Address[3]
                        , $PhoneString
                        , '<div button="edit-address" class="add-btn" number="' . $i . '">Edit</div>'
                        , '<div button="delete-address" class="add-btn" number="' . $i . '">Remove</div>'
                    );
                    $i++;
                }
                $tmpl = array (
                    'table_open'          => '<table class="list_show">',
                 );
                $CI->table->set_template($tmpl); 
                echo $CI->table->generate($data);
                ?>
            </div>
        </li>

        <li>
            <div id="add-edit-section">  

            </div>
        </li>

        <li>
            <div id="main-form-submit-btn" class="submit-bt">Save</div>
        </li>

    </ol>
</form>

<script src="<?php echo asset_url() . "js/string_helper.js" ?>"></script>
<?php include js_url(true) . 'validate_things.php' ?>
<script>
    /*--- Add website ------*/
    $("#add-website").on("click", function() {
        data = '<input class="text margin-bottom" name="Websites[]" placeholder="Website">';
        $("#websites-section").append(data);
        update_website_field();
    });
    $("#delete-website").on("click", function() {
        $("#websites-section input:last-child").remove();
    });

    var update_website_field = function() {
        $("input[name='Websites[]']").on("change", function() {
            value = $(this).val();
            if (!is_valid_url(value) && value.length > 0) {
                $(this).attr("class", "text-error margin-bottom");
                $("#website-error").text("Some field is not a valid URL");
            }
            else {
                $(this).attr("class", "text margin-bottom");
                $("#website-error").text("");
            }
        });
    }

    var validate_websites = function() {
        isPass = true;
        $("input[name='Websites[]']").each(function() {
            value = $(this).val();
            if (!is_valid_url(value) && value.length > 0) {
                $(this).attr("class", "text-error margin-bottom");
                $("#website-error").text("Some field is not a valid URL");
                isPass = false;
            }
            else {
                $(this).attr("class", "text margin-bottom");
                $("#website-error").text("");
            }
        });
        return isPass;
    }

    Locations = <?php echo json_encode($Locations); ?>;
    /*------- Add-Delete Phones -------*/
    update_phone_button = function() {
        $("#add-phone").on("click", function() {
            data = '<input class="text margin-bottom" type="text" placeholder="Phone" name="Phones[]">';
            $("#phone-section").append(data);
            update_phone_fields();
        });

        $("#delete-phone").on("click", function() {
            $("#phone-section input:last-child").remove();
            update_phone_fields();
        });

    }

    /*------ End of add-delete phones ------*/
    /*------- Validate Name -----------*/
    var update_name = function() {
        $("input[name='name']").on("change", function() {
            val = $(this).val();
            if (val.length == 0) {
                $(this).attr("class", "text margin-bottom");
                $("#name-error").text("Name is required");
            }
            else {
                $(this).attr("class", "text-error margin-bottom");
                $("#name-error").text("");
            }
        });
    }
    /*------- End of validate name -----*/
    /*------ Validate Phones --------*/
    var update_phone_fields = function() {
        $("input[name='Phones[]']").on('change', function() {
            value = $(this).val();
            value = value.toString();
            if ((value.match(/\d/) && value.length >= 10) || value.length === 0) {
                $(this).attr("class", "text margin-bottom");
            }
            else {
                $(this).attr("class", "text-error margin-bottom");
            }
        });
    }
    var validate_phones = function() {
        passPhone = true;
        $("input[name='Phones[]']").each(function() {
            value = $(this).val();
            if ((value.match(/\d/) && value.length >= 10) || value.length === 0) {

            }
            else {
                passPhone = false;
            }
        });
        if (passPhone === false) {
            $("#phone-error").text("Some phone fields is incorrect!");
        } else {
            $("#phone-error").text("");
        }
        return passPhone;
    }
    /* End of validate phone */
    /*Validate Address */
    var validate_address = function() {
        province = $("input[name='Province']").val();
        city = $("input[name='City']").val();
        district = $("input[name='District']").val();
        street = $("input[name='Street']").val();
        if (province.length == 0 && city.length == 0) {
            $("input[name='Province']").attr("class", "text-error margin-bottom");
            $("input[name='City']").attr("class", "text-error margin-bottom");
            $("#address-error").text("You can not leave both Province and City empty");
            return false;
        }
        else {
            $("input[name='Province']").attr("class", "text margin-bottom");
            $("input[name='City']").attr("class", "text margin-bottom");
            $("#address-error").text("");
        }

        if (district.length == 0) {
            $("input[name='District']").attr("class", "text-error margin-bottom");
            $("#address-error").text("You can not leave District empty");
            return false;
        }
        else {
            $("input[name='District']").attr("class", "text margin-bottom");
            $("#address-error").text("");
        }
        if (street.length == 0) {
            $("input[name='Street']").attr("class", "text-error margin-bottom");
            $("#address-error").text("You can not leave Street empty");
            return false;
        } else {
            $("input[name='Street']").attr("class", "margin-bottom");
            $("#address-error").text("");
        }

        return true;
    }
    /*------ End of Validate Address --------*/
    update = function() {
        update_phone_button();
        update_phone_fields();
    }
    /*------ Add new Address button ----*/
    var update_add_address_btn = function() {
        $("#add-address").on("click", function() {
            $("#currentid").val(-1);
            data = '<div class="head">Add New:</div>'
                    + '<div class="tab">'
                    + '<div class="head same-line" >Name : </div>'
                    + '<input id="name" name="name" class="text" type="text" placeholder="Name the contact">  <span id="name-error" class="error"></span>'
                    + '<div class="head">Address: <span class="error" id="address-error"></span></div>'
                    + '<div class="tab">'
                    + '<input class="text margin-bottom" type="text" placeholder="Province" name="Province" title="Province" /> '
                    + '<input class="text margin-bottom" type="text" placeholder="City" name="City"  title="City"/>'
                    + '<input class="text margin-bottom" type="text" placeholder="District" name="District" title="District"/> '
                    + '<input class="text margin-bottom" type="text" placeholder="Street" name="Street" title="Street"/> '
                    + '</div>'
                    + '<div class="head">Phone: (Opt)'
                    + '<div id="add-phone" class="margin-left add-btn" style="position:relative; left: 11%">+</div>'
                    + '<div id="delete-phone" class="margin-left add-btn" style="position:relative; left:16%">-</div>'
                    + '</div>'
                    +'<div style="width:100% display:inline-block">'
                    +'<div class="head">Google Embbed Link:</div>'
                    +'<textarea id="googlelink" name="GoogleLink" class="text" style="width:80%" placeholder="Copy and Paste your google embed code to this section"></textarea>'
                    +'</div>'
                    + '<div id="phone-section" class="tab"></div>'
                    + '<div class="head">Describtion: (Opt)</div>'
                    + '<div class="tab">'
                    + '<textarea id="Describtion" class="text" name="Describtion" placeholder="More detail about the address or phone" style="width:60%;"></textarea>'
                    + '</div>'
                    + '</div>';
            $("#add-edit-section").html(data);
            $(this).attr("id", "stop-add-edit-address");
            $(this).text("Not Add");
            update_stop_address_btn();
            update();
        });
    }
    var update_stop_address_btn = function() {
        $("#stop-add-edit-address").on("click", function() {
            $("#currentid").val(-2);
            $("#add-edit-section").html("");
            $(this).attr("id", "add-address");
            $(this).text("Add New");
            update_add_address_btn();
        });
    }

    update_add_address_btn();    
    /*------ End of add new address -----*/
    
    /*------ Edit or Remove address ------*/
    $('[button="edit-address"]').on("click", function() {
        var id = $(this).attr('number');
        id = parseInt(id);
        Location = Locations[id];
        $("#currentid").val(Location['ContactID']);
        //Input address value
        AddressArray = Location['Address'].split("#");
        data = ('<div class="head">Edit:</div>'
                + '<div class="tab">'
                + '<input id="name" name="name" class="text" type="text" placeholder="Name the contact" value="{0}">  <span id="name-error" class="error"></span>'
                + '<div class="head">Address: <span class="error" id="address-error"></div>'
                + '<div class="tab">'
                + '<input value="{1}" class="text margin-bottom" type="text" placeholder="Province" name="Province" title="Province" /> '
                + '<input value="{2}" class="text margin-bottom" type="text" placeholder="City" name="City"  title="City"/>'
                + '<input value="{3}" class="text margin-bottom" type="text" placeholder="District" name="District" title="District"/> '
                + '<input value="{4}" class="text margin-bottom" type="text" placeholder="Street" name="Street" title="Street"/> '
                + '</div>').format(Location["Name"].toString(), AddressArray[0], AddressArray[1], AddressArray[2], AddressArray[3]);
        //Input phone value
        data += '<div class="head">Phone: (Opt)'
                + '<div id="add-phone" class="margin-left add-btn" style="position:relative; left: 11%">+</div>'
                + '<div id="delete-phone" class="margin-left add-btn" style="position:relative; left:16%">-</div>'
                + '</div>'
                + '<div id="phone-section" class="tab">';
        PhoneArray = Location['Phones'].split("#");
        PhoneArray.forEach(function(value) {
            data += '<input value="{0}" class="text margin-bottom" type="text" placeholder="Phone" name="Phones[]">'.format(value);
        });
        data += ('</div>'
                +'<div style="width:100% display:inline-block">'
                +'<div class="head">Google Embbed Link:</div>'
                +'<textarea id="googlelink" name="GoogleLink" class="text" style="width:80%" placeholder="Copy and Paste your google embed code to this section">{0}</textarea>'
                +'</div>'
                + '<div id="phone-section" class="tab"></div>'
                + '<div class="head">Describtion: (Opt)</div>'
                + '<div class="tab">'
                + '<textarea id="Describtion" class="text" name="Describtion" placeholder="More detail about the address or phone" style="width:60%;">{1}</textarea>'
                + '</div>'
                + '</div>').format(Location['GoogleLink']?Location['GoogleLink']:"",Location['Describtion']?Location['Describtion']:"");
        $("#add-edit-section").html(data);
        //Stop Add button
        $("#add-address").attr("id", "stop-add-edit-address").text("Not Add");
        update_stop_address_btn();
        //------------
        update();
    });
    
    $('[button="delete-address"]').on("click", function() {
        var id = $(this).attr('number');
        id = parseInt(id);   
        ConfirmDialog("Are you sure to delete?", id);
    });
    
    function delete_address(id){
        Location = Locations[id];
        url_link = "<?php echo site_url()."/user_group2/account/delete_user_contact"?>";
        var result;
        $.ajax({
            url : url_link,
            type: 'post',
            async: false,
            data: { ID : Location['ContactID']},
            success: function(data){
                result = data;
            } 
        });
        if(result == 1 || result == '1'){
            $('div[number='+id+']').parent().parent().remove();
        }
    }
    
    function ConfirmDialog(message, id){
    $('<div></div>').appendTo('body')
                    .html('<div><h6>'+message+'?</h6></div>')
                    .dialog({
                        modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
                        width: 'auto', resizable: false,
                        buttons: {
                            Yes: function () {
                                // $(obj).removeAttr('onclick');                                
                                // $(obj).parents('.Parent').remove();

                                $(this).dialog("close");
                                delete_address(id);
                            },
                            No: function () {
                                $(this).dialog("close");
                            }
                        },
                        close: function (event, ui) {
                            $(this).remove();
                        }
                    });
    };
    /*---- End of edit-remove Address -------*/
    $("#main-form-submit-btn").on("click", function() {
        isPass = true;
        var id = $("#currentid").val();
        id = parseInt(id);
        if (id != -2) {
            if (!validate_phones())
                isPass = false;
            if (!validate_address())
                isPass = false;
        }
        if (!validate_websites())
            isPass = false;
        if (isPass) {
            $("form#edit-user-contact-form").submit();
        }
    });
</script>

